﻿using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;

namespace DrawTools.Controls.ColorSelector
{
  public partial class ColorSelectorControl : UserControl
  {
    private const int RECT_WIDTH = 10;
    private const int RECT_HEIGHT = 8;

    public Color[] Palette { get; set; }

    public ColorSelectorControl()
    {
      InitializeComponent();
      Palette = new Color[0];
    }

    protected override void OnPaintBackground(PaintEventArgs e)
    {
      base.OnPaintBackground(e);

      //e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
      //e.Graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;

      var rect = new Rectangle(0, 0, RECT_WIDTH, RECT_HEIGHT);
      rect.Offset(Width - RECT_WIDTH - 1, Height - RECT_HEIGHT);

      var pt1 = new Point(rect.Left + 1, rect.Top + 2);
      var pt2 = new Point(rect.Right - 1, rect.Top + 2);
      var pt3 = new Point(rect.Left + rect.Width / 2, rect.Bottom - 2);

      var path = new GraphicsPath();
      path.AddLine(pt1, pt2);
      path.AddLine(pt2, pt3);
      path.AddLine(pt3, pt1);

      e.Graphics.DrawRectangle(Pens.DimGray, new Rectangle(ClientRectangle.X, ClientRectangle.Y, ClientRectangle.Width - 1, ClientRectangle.Height - 1));
      e.Graphics.FillRectangle(Brushes.DimGray, rect);
      e.Graphics.FillPath(Brushes.LightGray, path);
    }

    protected override void OnClick(EventArgs e)
    {
      Color oldColor = BackColor;

      var popup = new ColorSelectorPopup(Palette, oldColor);
      popup.ColorSelected += (o, args) => BackColor = args.SelectedColor;
      popup.RestoreColor += (o, args) => BackColor = oldColor;
      popup.Show(this, new Point(0, Height));
    }
  }
}